﻿using System;
using System.Collections.Generic;
using System.Linq;
using Coolite.Ext.Web;
using Newtonsoft.Json.Linq;
using Pap.Core.Utilities;
using Pap.Services.WorkflowEngine;
using Pap.Web.Modules.Loan.ViewModel;
using Pap.Web.Utils;
using Utils;

namespace Pap.Web.Modules.Loan.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class ResponsibleSocialFeasibilityWaitingList : BaseUserControl<ResponsibleSocialFeasibilityWaitingListViewModel>
    {
        /// <summary>
        /// Gets or sets the freez loans.
        /// </summary>
        /// <value>
        /// The freez loans.
        /// </value>
        private Dictionary<Guid, DateTime> FreezLoans
        {
            get { return (Dictionary<Guid, DateTime>)ViewState["FreezLoans"]; }
            set { ViewState["FreezLoans"] = value; }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Ext.IsAjaxRequest && !IsPostBack)
            {
                if (ViewModel != null)
                {
                    var loans = this.ViewModel.GetLoansForCurrentResponsible(RegistryInfo.CommitteeID, RegistryInfo.UserID);
                    storeResearchLoans.DataSource = loans;
                    storeResearchLoans.DataBind();

                    var actionList = from action in this.ViewModel.GetAvailableDecisions()
                                     where Enums.ToString(action) != Enums.ToString(ActionTypes.RefusedFromBegining)
                                     select new
                                     {
                                         DecisionID = Enums.ToString(action),
                                         DecisionName = Enums.ToString(action, GetLocalResourceObject("LanguageIndex").ToInt32())
                                     };

                    storeResearchDecisions.DataSource = actionList;
                    storeResearchDecisions.DataBind();

                    dtFreezDate.MinDate = DateTime.Now.AddDays(1);
                    FreezLoans = new Dictionary<Guid, DateTime>();
                }
            }
        }

        /// <summary>
        /// Handles the Clicked event of the BtnSubmitDecisions control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnSubmitDecisions_Clicked(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["grvLoans"] != null)
            {
                string jsonString = e.ExtraParams["grvLoans"];
                JArray jarray = JSON.Deserialize(jsonString) as JArray;

                Dictionary<string, int> actionTypes = Enums.ToNameKeyPaires(typeof(ActionTypes));
                List<ActionTypes> loanDecisions = new List<ActionTypes>();
                List<Guid> loansIDs = new List<Guid>();
                List<string> Notes = new List<string>();
                List<DateTime?> freezdDates = new List<DateTime?>();
                List<string> errorsLoansNumbers = new List<string>();

                for (int i = 0; i < jarray.Count; i++)
                {
                    if (!string.IsNullOrEmpty(jarray[i]["DecisionID"].ToString().Trim('"')))
                    {
                        ActionTypes action = (ActionTypes)actionTypes[jarray[i]["DecisionID"].ToString().Trim('"')];
                        if ((action.Equals(ActionTypes.Refuse) || action.Equals(ActionTypes.Freeze)) || action.Equals(ActionTypes.Submit))
                        {
                            string notes = string.Empty;
                            if (jarray[i]["Notes"] != null)
                            {
                                notes = (jarray[i]["Notes"].ToString().Trim('"').Replace("\\n", "\r\n"));
                            }
                            if (!notes.IsNullOrEmpty())
                            {
                                if (action.Equals(ActionTypes.Freeze))
                                {
                                    if (FreezLoans.Any(
                                         loan => loan.Key.Equals(jarray[i]["LoanID"].ToString().Trim('"').ToGuid())))
                                    {
                                        freezdDates.Add(
                                            FreezLoans[jarray[i]["LoanID"].ToString().Trim('"').ToGuid()]);
                                        loanDecisions.Add(action);
                                        loansIDs.Add(jarray[i]["LoanID"].ToString().Trim('"').ToGuid());
                                        Notes.Add(notes);
                                    }
                                }
                                else
                                {
                                    loanDecisions.Add(action);
                                    loansIDs.Add(jarray[i]["LoanID"].ToString().Trim('"').ToGuid());
                                    freezdDates.Add(null);
                                    Notes.Add(notes);
                                }
                            }
                            else
                            {
                                errorsLoansNumbers.Add(jarray[i]["LoanNumber"].ToString().Trim('"'));
                            }

                        }
                        else
                        {
                            loanDecisions.Add(action);
                            loansIDs.Add(jarray[i]["LoanID"].ToString().Trim('"').ToGuid());
                            freezdDates.Add(null);
                            if (jarray[i]["Notes"] != null)
                                Notes.Add(jarray[i]["Notes"].ToString().Trim('"').Replace("\\n", "\r\n"));
                            else
                                Notes.Add(string.Empty);
                        }
                    }
                }


                if (loanDecisions.Count > 0)
                {
                    this.ViewModel.TakeLoanDecisions(loansIDs, loanDecisions, Notes, freezdDates);
                    RefreshControl();

                    if (LoansSubmitted != null)
                        LoansSubmitted(this, new AjaxEventArgs(new Coolite.Ext.Web.ParameterCollection()));
                }
                if (errorsLoansNumbers.Count > 0)
                {
                    string[] loansNumbers = errorsLoansNumbers.ToArray();
                    string errorloans = String.Join(", ", loansNumbers);

                    Ext.Msg.Configure(new MessageBox.Config
                    {
                        Title = GetLocalResourceObject("MBError").ToString(),
                        Message = GetLocalResourceObject("MBErrorLoans").ToString() + " " + errorloans,
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.ERROR
                    }).Show();
                }
            }

        }

        /// <summary>
        /// Handles the Command event of the gvrLoans control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void gvrLoans_Command(object sender, AjaxEventArgs e)
        {
            switch (e.ExtraParams["CommandName"])
            {
                case "ViewLoan":
                    this.RedirectFromThisPage("Loan", "createloan", "LoanID=" + e.ExtraParams["LoanID"]);
                    break;

                case "ViewFeasabilityStudy":
                    this.RedirectFromThisPage("Loan", "LoanResearchAndStudy", "LoanID=" + e.ExtraParams["LoanID"]);
                    break;

                case "ViewSocialResearch":
                    this.RedirectFromThisPage("Loan", "LoanResearchAndStudy", "LoanID=" + e.ExtraParams["LoanID"]);
                    break;
            }
        }

        /// <summary>
        /// Handles the AfterEdit event of the gvrLoans control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void gvrLoans_AfterEdit(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["DecisionID"] != null && e.ExtraParams["LoanID"] != null && e.ExtraParams["FieldName"] != null)
            {
                if (e.ExtraParams["FieldName"].Equals("DecisionID"))
                {
                    Guid decisionID = e.ExtraParams["DecisionID"].ToGuid();
                    Guid loanID = e.ExtraParams["LoanID"].ToGuid();
                    if (decisionID.Equals(Enums.ToString(ActionTypes.Freeze).ToGuid()))
                    {
                        txtHidenLoanID.Text = loanID.ToString();
                        wndFreezDate.Show();
                    }
                    else
                    {
                        FreezLoans.Remove(loanID);
                    }
                }
            }
        }

        /// <summary>
        /// Handles the Clicked event of the BtnSaveFreezDate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnSaveFreezDate_Clicked(object sender, AjaxEventArgs e)
        {
            FreezLoans.Add(txtHidenLoanID.Text.ToGuid(), Convert.ToDateTime(dtFreezDate.Value));
            txtHidenLoanID.Reset();
            dtFreezDate.Reset();
            wndFreezDate.Hide();
        }

        /// <summary>
        /// Occurs when [loans submitted].
        /// </summary>
        public event EventHandler<AjaxEventArgs> LoansSubmitted;

        /// <summary>
        /// Refreshes the control.
        /// </summary>
        public void RefreshControl()
        {
            var loans = this.ViewModel.GetLoansForCurrentResponsible(RegistryInfo.CommitteeID, RegistryInfo.UserID);
            storeResearchLoans.DataSource = loans;
            storeResearchLoans.DataBind();
        }
    }
}